package cn.edu.hitwh.resume.web.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import cn.edu.hitwh.resume.dal.dao.AdminDao;
import cn.edu.hitwh.resume.dal.entity.AdminDo;

@Controller
public class AdminController {

	@Autowired
	AdminDao adminDao;
	
	@RequestMapping(value = {"/admin", "/admin/", "/admin/index"})
	public String index(HttpSession session, ModelMap model) {
		Object user = session.getAttribute("admin");
		if (null == user) {
			return "redirect:/admin/login";
		} else {
			model.put("user", user);
			return "page/admin/index";
		}
	}
	
	@RequestMapping(value = "/admin/login", method = RequestMethod.GET)
	public String loginPage() {
		return "page/admin/login";
	}

	@RequestMapping(value = "/admin/login", method = RequestMethod.POST)
	public String loginAction(@RequestParam(value = "name") String name,
							   @RequestParam(value = "pwd") String pwd,
							   HttpSession session,
							   ModelMap model) {
		AdminDo admin = this.adminDao.retriveByName(name);
		if (null == admin) {
			model.put("msg", "Name does not exist");
			return "page/admin/login";
		} else {
			if (admin.getPwd().equals(pwd)) {
				session.setAttribute("admin", admin);
				return "redirect:/admin/index";
			} else {
				model.put("msg", "Password is incorrect");
				return "page/admin/login";
			}
		}
	}
	
	@RequestMapping(value = "/admin/logout")
	public String logout(HttpSession session) {
		session.invalidate();
		return "page/admin/login";
	}
	
}
